
import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, Modal, InputNumber, ConfigProvider, message, Spin } from 'antd';
import { ColumnProps } from 'antd/es/table';
import * as moment from 'moment';
import './index.scss';
import 'moment/locale/zh-cn';

import { Link } from "react-router-dom";
import zhCN from 'antd/es/locale/zh_CN';
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';
import { dynamicsService } from "../../../../../services/services";
// 导出
import ExportCsv from "../../common/export";

// 台账合同
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';

import { isHavePermission, isHavePathPermission } from '../../utils/utils'
moment.locale('zh-cn');
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
interface DataType {
  key: React.Key;
  number: string;
  name: string;
  handle: string;
  relative: string;
  dependent: string;
  time: string;
}
interface fromdata {
  field: string;
  text: string;
  errorMessage: string;
  required: boolean;
  type: string;
  value: any;
  options: any;
  theType: any;
  header: any;
  conditions: any;
}
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const columns: ColumnProps<DataType>[] = [
  {
    title: '案件编号',
    dataIndex: 'Title',
    key: 'Title',
    align: 'center',
    render(text) {
      let _this = this
      return (
        <div>
          {
            // < a onClick={() => on(text)}>{text}</ a>
            <Link to={{ pathname: 'CaseManagement', state: { id: text, page: 'SearchCase' } }}>{text}</Link>
          }
        </div>
      )
    },
  },
  {
    title: '案件受理日',
    dataIndex: 'AcceptTime',
    key: 'AcceptTime',
    align: 'center',
    // render: text => <div>{text === null ? text : text.slice(0, 10) + ' ' + text.slice(11, 19)}</div>,
  },
  {
    title: '案件名称',
    dataIndex: 'CaseName',
    key: 'CaseName',
    align: 'center',
  },
  // {
  //   title: '相对方',
  //   dataIndex: 'Counterparty',
  //   key: 'Counterparty',
  //   align: 'center',
  // },
  {
    title: '社内依赖者名',
    dataIndex: 'RelierName',
    key: 'RelierName',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'Created',
    key: 'Created',
    align: 'center',
    // render: text => <div>{text.slice(0, 10)} {text.slice(12, 19)}</div>,
    // render: text => <div>{text === null ? text : text.slice(0, 10) + ' ' + text.slice(11, 19)}</div>,
  },
  {
    title: '创建者',
    dataIndex: 'AuthorName',
    key: 'AuthorName',
    align: 'center',
    // render: text => <div>{text === null ? text : text.slice(0, 10) + ' ' + text.slice(11, 19)}</div>,

  }
]

const fromData: fromdata[] = [
  {
    field: 'bianhao',
    text: '案件编号',
    errorMessage: '请选择日期',
    required: false,
    type: 'bianhao',
    value: null,
    options: [],
    theType: 'bianhao',
    header: "LastAnswerTime",
    conditions: "Eq",
  }, {
    field: 'number',
    text: '依赖者名',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "RelierName",
    conditions: "Contains",
  }, {
    field: 'chuangjian',
    text: '创建日期',
    errorMessage: '请选择日期',
    required: false,
    type: 'chuangjian',
    value: null,
    options: [],
    theType: 'chuangjian',
    header: "LastAnswerTime",
    conditions: "Eq",
  },
  {
    field: 'customer',
    text: '案件类型',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "CaseType",
    conditions: "Eq",
  }, {
    field: 'jobid',
    text: '案件受理日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "AcceptTime",
    conditions: "Ge",
  }, {
    field: 'nature',
    text: '法务意见书',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "OpinionBook",
    conditions: "Eq",
  }, {
    field: 'relyOn',
    text: '案件最后回答日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "LastAnswerTime",
    conditions: "Ge",
  }, {
    field: 'modify',
    text: '律师咨询/参加',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "HasLawyer",
    conditions: "Eq",
  }, {
    field: 'mingcheng',
    text: '案件名称',
    errorMessage: '请选择日期',
    required: false,
    type: 'mingcheng',
    value: null,
    options: [],
    theType: 'mingcheng',
    header: "LastAnswerTime",
    conditions: "Contains",
  }, {
    field: 'modifys',
    text: '保密',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "NeedSecrecy",
    conditions: "Eq",
  }, {
    field: 'company',
    text: '案件概要',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "CaseSummary",
    conditions: "Contains",
  }, {
    field: 'Lawyerreview',
    text: '其它',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "Other",
    conditions: "Contains",
  },{
    field: 'suoshu',
    text: '所属公司',
    errorMessage: '请输入',
    required: false,
    type: 'selectss',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "BelongsCompany",
    conditions: "Eq",
  }, {
    field: 'shouli',
    text: '受理担当',
    errorMessage: '请选择日期',
    required: false,
    type: 'shouli',
    value: null,
    options: [],
    theType: 'shouli',
    header: "LastAnswerTime",
    conditions: "Eq",
  } 
]

const formItemLayout = {
  labelCol: {
    span: 7,

  },
  wrapperCol: {
    offset: 0,
    span: 17,
  },
}
class SearchCase extends React.Component<FormComponentProps> {
  constructor(props: any) {
    super(props);
  }
  /**
* 根据后台返回的 data 中 type 类型生成不同的组件
* @param item  json
* @param Component
*/
  switchItem(item) {
    let defaultDateValue = [];
    if(this.state.form.dateOf != "" && this.state.form.dateOf1 != null){
      
      defaultDateValue = [
        moment(this.state.form.dateOf, dateFormat),
        moment(this.state.form.dateOf1, dateFormat),
      ];
    }
    const type = item.type;
    switch (type) {
      case 'Picker':
        return <RangePicker allowClear format={dateFormat} />;
      case 'int':
        return <InputNumber style={{ width: '100%' }} />;
      case 'char':
        return <Input allowClear style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'date':
        return <DatePicker allowClear format={dateFormat} style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'select':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.Title} key={option.Title}>{option.Title}</Option>)
              })
            }
          </Select>
        )
      case 'selects':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.Title} key={option.Title}>{option.Title}</Option>)
              })
            }
          </Select>
        )
        case 'selectss':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option} key={option}>{option}</Option>)
              })
            }
          </Select>
        )
      case 'multiSelect':
        return (
          <Select allowClear mode='multiple' maxTagCount={1} style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.username} key={option.ID}>{option.username}</Option>)
              })
            }
          </Select>
        )
      case 'bianhao':
        return (
          <Input.Group compact>
            <Input allowClear style={{ width: '45%', marginRight: 0, textTransform: 'uppercase' }} placeholder="请输入"
              onChange={(event) => { this.change(event, "contract1") }}
              value={this.state.form.contract1} />
            <Input
              className="site-input-split"
              style={{
                width: '10%',
                background: 'white',
                pointerEvents: 'none',
                border: 'none',
              }}
              placeholder="~"
              disabled
            />
            <Input
              className="site-input-right"
              style={{
                width: ' 45%',
              }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "contract2") }}
              value={this.state.form.contract2}
            />
          </Input.Group>
        )
      case 'chuangjian':
        return (
          <Input.Group compact>
            <RangePicker allowClear
              style={{ width: '100%' }}
              onChange={this.onChangeRangeDate}
              format={"YYYY-MM-DD"}
              defaultValue={defaultDateValue}
              placeholder={['选择开始日期', '选择结束日期']}
            />
          </Input.Group>
        )

      case 'mingcheng':
        return (
          <Input.Group compact>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "contractName") }}
              value={this.state.form.contractName}
            />
          </Input.Group>
        )
      case 'shouli':
        return (
          <Input.Group compact>
            <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '100%' }} value={this.state.form.personreview}
              onChange={(event, value) => { this.handleSelectChanges(event, value, "personreview") }} maxTagCount={2}>
              {
                this.state.personreviewList.map(element => {
                  return <Option value={element.username} key={element.ID}>{element.username}</Option>
                })
              }
            </Select>
          </Input.Group>
        )
      case 'suoshu':
        return (
          <Input.Group compact>
            <Input
              className="site-input-right"
              style={{
                width: '100%',
              }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "min") }}
              value={this.state.form.min}
            />
          </Input.Group>
        )
      default:
        return <Input allowClear />;
    }
  }
  list = ['测试数据', '测试数据1'];
  state = {
    ExportCsvVisible: false,
    exportData: {
      filename: '案件导出',//文件名称
      parentElName: 'Button_2',//父元素类名
      elClassName: 'custom',//当前点击元素类名
      dowloadText: '导出CSV',
      headers: [//表头 key 对应data的属性
        { label: "案件编号", key: "Title" },
        { label: "案件受理日", key: "AcceptTime" },
        { label: "案件最后回答日", key: "LastAnswerTime" },
        { label: "案件名称", key: "CaseName" },
        { label: "案件概要", key: "CaseSummary" },
        { label: "所属公司", key: "BelongsCompany" },
        { label: "依赖者名", key: "RelierName" },
        { label: "案件类型", key: "CaseType" },
        { label: "法务意见书", key: "OpinionBook" },
        { label: "律师咨询/参加", key: "HasLawyer" },
        { label: "保密", key: "NeedSecrecy" },
        { label: "其它", key: "Other" },
        { label: "受理担当", key: "Acceptor" },
        { label: "创建者", key: "AuthorName" },
        { label: "创建时间", key: "Created" },
      ],
      isLoading: true,
      data: [//数据源

      ]
    },
    filter: [],
    pager: {
      current: 1,
      size: 10
    },
    pageSize: 10,
    paging: 0,
    loading: false,
    inSearchOf: false,
    local: zhCN,
    arr: '',
    // 记录条件个数
    arrSize: 0,
    data: [],
    size: '',
    // 总数据
    totalnumber: [],
    // 总数据数
    totalnum: 0,
    //表单数据对象
    retrieveList: [],
    typesofCasesList: [],
    form: {
      typesofCases: undefined,
      list: [],
      year: null,
      month: null,
      rangeTime: [],
      // 合同编号1
      contract1: null,
      // 合同编号2
      contract2: null,
      // 创建日期
      dateOf: "",
      // 结束时间
      dateOf1: "",
      // 合同名称
      contractName: null,
      // 我方
      min: undefined,
      // 相对方
      otherSide: null,
      // 审查担当
      personreview: undefined,
    },
    visible: false,
    confirmLoading: false,
    //审查担当
    personreviewList: [],
    weList: [],
  }

  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission()

    let isBack:any;
    isBack = this.props;

    
    // 

    if (isBack.location.state != undefined) {
      let form = JSON.parse(localStorage.getItem('searchForm')); //检索编号
      let formParams = JSON.parse(localStorage.getItem('searchFormParams')); //高级检索
      let PageIndex = JSON.parse(localStorage.getItem('PageIndex')); // 页码
      let searchType = localStorage.getItem('searchType'); // 检索类型
      let pager = this.state.pager;
      pager.current = PageIndex;
      this.setState(pager);

      
      
      
      
      if(form != null){
        this.setState({form},()=>{
          if (searchType != '无文件') {
            this.retrieve(searchType, 1);
          }else if(searchType == '无文件'){
            this.noFile(1);
          }
          // localStorage.removeItem('searchForm');
        });
      }else if(formParams != null){
        let params = formParams[0].where;
        this.setParamsByCache(params); //高级检索缓存赋值
        this.theQuery(formParams, 1);
      }else{
        this.getData();
      }
      // this.setState({ form })
    }else{
      localStorage.removeItem('searchForm');
      localStorage.removeItem('searchType');
      localStorage.removeItem('searchFormParams');

      fromData.forEach((item, index)=>{
        fromData[index].value = undefined
      })
      
      this.getData();
    }

    this.getTest();// 测试代码，调试API使用
    // this.getTest1();// 测试代码，调试API使用
  }


  setParamsByCache(params:any) {
    let form = this.state.form;

    fromData.forEach((item, index)=>{
      fromData[index].value = undefined
    })

    params.forEach(function(item, index) {
      let key = item.key;
      let type = item.filterType;
      let value = item.value;
      for(let i = 0; i < fromData.length; i++){
        let field = fromData[i].field;

        if(key == '' && type == 'CaseNum'){ //案件编号
          if (value.indexOf('|') > -1) {
            let num = value.split('|');
            form.contract1 = num[0];
            form.contract2 = num[1];
          }else{
            form.contract1 = value;
          }
          
        }else if(key == 'RelierName' && field == 'number'){ //依赖者名
          fromData[i].value = value;
        }else if(key == 'Created' && type == 'Ge'){ //创建时间
          form.dateOf = value;
        }else if(key == 'Created' && type == 'Le'){ //创建时间
          form.dateOf1 = value;
        }else if(key == 'CaseType' && field == 'customer'){ //案件类型
          fromData[i].value = value;
        }else if(key == 'AcceptTime' && field == 'jobid'){ //案件受理日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'OpinionBook' && field == 'nature'){ //法务意见书
          fromData[i].value = value;
        }else if(key == 'LastAnswerTime' && field == 'relyOn'){ //案件最后回答日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'HasLawyer' && field == 'modify'){ //律师咨询/参加
          fromData[i].value = value;
        }else if(key == 'CaseName' && field == 'mingcheng'){ //案件名称
          form.contractName = value;
        }else if(key == 'NeedSecrecy' && field == 'modifys'){ //保密
          fromData[i].value = value;
        }else if(key == 'CaseSummary' && field == 'company'){ //案件概要
          fromData[i].value = value;
        }else if(key == 'Acceptor' && field == 'shouli'){ //受理担当
          let valArr = [];
          valArr = value.split(';');
          form.personreview = valArr;
        }else if(key == 'BelongsCompany' && field == 'suoshu'){ //所属公司
          fromData[i].value = value;
        }else if(key == 'Other' && field == 'Lawyerreview'){ //其它
          fromData[i].value = value;
        }
      }
    });
    this.setState({form},()=>{
      
      
    });
  }


  onChange = (e, key) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e
      }
    })
  }

  // 下拉框改变赋值
  handleSelectChange = (e, key) => {
    this.setState({
      form: {
        key: e,
        ...this.state.form,
        [key]: e
      }
    })
  }

  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var array = []
    var arrays = []
    v.forEach(element => {
      array.push(element.key)
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    this.setState({
      form: {
        ...this.state.form,
        reviewOn: array.join(","),
        reviewOnxuans: arrays.join(';'),
        [key]: e,
        "list": v,
      }
    })
  }

  //弹框取消
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  // 输入框改变赋值
  change(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e.target.value
      }
    })
  }

  // 获取日期
  onChangeRangeDate = (value, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        "dateOf": dateString[0] ? dateString[0] + ' 00:00:00' : '',
        "dateOf1": dateString[1] ? dateString[1] + ' 23:59:59' : ''
      }
    })

  }

  //无文件检索 
  noFile = (isBack = 0) => {
    localStorage.setItem('searchType', '无文件')
    this.setState({
      loading: true
    })
    // 清空检索内容
    // this.ContentToEmpty()
    // 清空选中条件
    // let params: CamlParam[] = [];
    let params: any = [
      {
        logic: "and",
        where: [

        ]
      }
    ];

    // (file[jay].FSObjType == 1 && file[jay].FileRef.indexOf(element.FileAddress) != -1 && file[jay].Folder.ItemCount == 0
    params[0].where.push({
      key: '',
      filterType: "EmptyFolder",
      value: 1
    })
    if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.personreview != undefined && this.state.form.personreview != null && this.state.form.personreview.length != 0)) {
      params[0].where.push( {
        key: 'Acceptor',
        filterType: "MultiUsers",
        value: this.state.form.personreview.map(i => i.replace("-历史","")).join(';')
      })
    }

    localStorage.removeItem('searchFormParams'); //删除高级检索的条件缓存
    let form = this.state.form;
      // 
    
    
    if (form.personreview == undefined) {
      localStorage.setItem('searchForm', JSON.stringify(form));
    }else{
      // localStorage.setItem('searchFormList', JSON.stringify(form.list));
      form.list = [];
      localStorage.setItem('searchForm', JSON.stringify(form));
    }

    this.theQuery(params, isBack)
  }

  //弹框确定
  handleSubmit = (e) => {
    this.setState({
      loading: true
    })
    localStorage.removeItem('searchForm'); //删除普通检索的条件缓存
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 清空选中条件
        // let params: CamlParam[] = [];
        let params: any = [
          {
            logic: "and",
            where: [
              {
                key: 'CaseStatus',
                filterType: "Eq",
                value: "有效"
              }
            ]
          }
        ];

        for (let i = 0; i < fromData.length; i++) {

          let size = fromData[i].field + ""

          // 是否是 有开始时间结束时间
          let istrue = false

          if (size == "bianhao") {

            // 判断合同编号1 合同编号2 是否 都有值 
            // 在两输入框全部输入执行 查流水号区间
            if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

              let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;


              let number1 = this.state.form.contract1
              let number2 = this.state.form.contract2
              //
              /** ------------------------------------    因为可能会存在老系统的编号不支持新的编号规则 所以先去掉       ------------------------------------------------ */
              // if (this.state.form.contract1.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract1)) {
              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件


              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })
              //     // params[0].where.push({
              //     //   key: 'VersionNum',
              //     //   filterType: "Ge",
              //     //   value: AfterTheNumber
              //     // })

              //     number1 = this.state.form.contract1


              //   } else {
              //     message.warning('编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // } else {
              //   if (pattern.test(this.state.form.contract1)) {
              //     // contract1
              //     // 截取编号最后三位流水号
              //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
              //     // 我方
              //     var our = this.state.form.contract1.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)

              //     // params.push({
              //     //   item1: 'Our',
              //     //   item2: 'AcceptYear',
              //     //   item3: 'SerialNum',
              //     //   text1: our,
              //     //   text2: year,
              //     //   text3: serialNumber,
              //     //   type: "contractNo2"
              //     // })
              //     // params[0].where.push({
              //     //   key: 'Our',
              //     //   filterType: "Eq",
              //     //   value: our
              //     // })
              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })

              //     number1 = this.state.form.contract1

              //   } else {
              //     message.warning('编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // }

              // if (this.state.form.contract2.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract2)) {
              //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

              //     //
              //     //
              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件
              //     //  我方
              //     // params.push(new CamlParam("Our", our, SPDataType.Text, CAMLCompare.Eq));
              //     // 年份
              //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
              //     //  版本号
              //     // params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

              //     // params[0].where.push({
              //     //   key: 'Our',
              //     //   filterType: "Eq",
              //     //   value: our
              //     // })
              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })
              //     // params[0].where.push({
              //     //   key: 'VersionNum',
              //     //   filterType: "Ge",
              //     //   value: AfterTheNumber
              //     // })

              //     number2 = this.state.form.contract2

              //   } else {
              //     message.warning('编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // } else {
              //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
              //   if (pattern.test(this.state.form.contract2)) {
              //     // contract2
              //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
              //     let serialNumber2 = str2.substring(str2.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber2 = parseInt(serialNumber2)
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于

              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Le",
              //     //   value: serialNumber2
              //     // })

              //     number2 = this.state.form.contract2


              //   } else {
              //     message.warning('编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // }
              /** ------------------------------------    End       ------------------------------------------------ */
              if (pattern1.test(this.state.form.contract1)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: number1 + "|" + number2
                })
              } else {
                  message.warning('编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false,
                  })
                  return
              }
              



            } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract1)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
              //   // params.push({
              //   //   item: 'Title',
              //   //   text: this.state.form.contract1,
              //   //   type: "indexOf"
              //   // })

              //   // params[0].where.push({
              //   //   key: 'Title',
              //   //   filterType: "Contains",
              //   //   value: this.state.form.contract1
              //   // })
              //   params[0].where.push({
              //     key: '',
              //     filterType: "CaseNum",
              //     value: this.state.form.contract1
              //   })

              // } else {
              //   message.warning('编号格式有误');
              //   this.setState({
              //     loading: false,
              //     inSearchOf: false,
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract1)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: this.state.form.contract1
                })
              } else {
                  message.warning('编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false,
                  })
                  return
              }
              

            } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract2)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
              //   // params.push({
              //   //   item: 'Title',
              //   //   text: this.state.form.contract2,
              //   //   type: "indexOf"
              //   // })

              //   // params[0].where.push({
              //   //   key: 'Title',
              //   //   filterType: "Contains",
              //   //   value: this.state.form.contract2
              //   // })
              //   params[0].where.push({
              //     key: '',
              //     filterType: "CaseNum",
              //     value: this.state.form.contract2
              //   })

              // } else {
              //   message.warning('编号格式有误');
              //   this.setState({
              //     loading: false
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract2)) {
                params[0].where.push({
                  key: '',
                  filterType: "CaseNum",
                  value: this.state.form.contract2
                })
              } else {
                message.warning('编号格式有误');
                this.setState({
                  loading: false,
                  inSearchOf: false,
                })
                return
              }
              
            }


          } else if (size == "mingcheng") {
            // 合同名称
            if (this.state.form.contractName != null && this.state.form.contractName != "") {
              // this.fuzzy("ContractName", this.state.form.contractName, "Text", "", "")
              // params.push(new CamlParam("CaseName", this.state.form.contractName, SPDataType.Text, CAMLCompare.Contains));
              params[0].where.push({
                key: 'CaseName',
                filterType: "Contains",
                value: this.state.form.contractName
              })
            }
          } else if (size == "shouli") {
            // 法务受理担当
            if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.personreview != undefined && this.state.form.personreview != null && this.state.form.personreview.length != 0)) {
              // for (let i = 0; i < this.state.form.list.length; i++) {
              //   // params.push(new CamlParam("Acceptor", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));
              //   params[0].where.push({
              //     key: 'Acceptor',
              //     filterType: "Contains",
              //     value: this.state.form.list[i].props.value.replace("-历史","")
              //   })

              // }
              params[0].where.push( {
                key: 'Acceptor',
                filterType: "MultiUsers",
                value: this.state.form.personreview.map(i => i.replace("-历史","")).join(';')
              })
            }
          }
          // else if (size == "suoshu") {
          //   // 所属公司
          //   if (this.state.form.min != null && this.state.form.min != "") {
          //     // this.fuzzy("Our", this.state.form.min, "Text", "", "")
              
          //     // params.push(new CamlParam("BelongsCompany", this.state.form.min, SPDataType.Text, CAMLCompare.Contains));
          //     params[0].where.push({
          //       key: 'BelongsCompany',
          //       filterType: "Eq",
          //       value: this.state.form.min
          //     })
              
          //   }
          // } 
          else if (size == "chuangjian") {
            // 开始日期
            if (this.state.form.dateOf != "" && this.state.form.dateOf1 != null) {
              // 2022-10-20T00:00:00Z
              let size = this.state.form.dateOf
              let size1 = this.state.form.dateOf1
              // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Geq));//我这里用的大于等于，你根据你实际情况来

              params[0].where.push({
                key: 'Created',
                filterType: "Ge",
                value: size
              })
              params[0].where.push({
                key: 'Created',
                filterType: "Le",
                value: size1
              })
            }

            //结束日期
            // if (this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null) {
            //   let size = this.state.form.dateOf1
            //   params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
            // }
          } else {

            if (size == "jobid" && values.jobid != null && values.jobid != undefined && values.jobid != "") {
              values.jobid = moment(values.jobid).format('YYYY-MM-DD')
              values.jobid = values.jobid
            }

            if (size == "relyOn" && values.relyOn != null && values.relyOn != undefined && values.relyOn != "") {
              values.relyOn = moment(values.relyOn).format('YYYY-MM-DD')
              values.relyOn = values.relyOn
            }


            if (size == "Legalacceptancedate" && values.Legalacceptancedate != null && values.Legalacceptancedate != undefined && values.Legalacceptancedate != "") {
              values.Legalacceptancedate[0] = moment(values.Legalacceptancedate[0]).format('YYYY-MM-DD')
              values.Legalacceptancedate[0] = values.Legalacceptancedate[0]

              values.Legalacceptancedate[1] = moment(values.Legalacceptancedate[1]).format('YYYY-MM-DD')
              values.Legalacceptancedate[1] = values.Legalacceptancedate[1]
              istrue = true
              // moment(values.Legalacceptancedate).format('YYYY-MM-DD')
              // values.Legalacceptancedate = values.Legalacceptancedate
            }

            if (values[`${size}`] != null && values[`${size}`] != undefined && values[`${size}`] != "") {
              if (!istrue) {
                // params.push(new CamlParam(fromData[i].header, values[`${size}`], SPDataType[`${fromData[i].theType}`], CAMLCompare[`${fromData[i].conditions}`]));

                params[0].where.push({
                  key: fromData[i].header,
                  filterType: fromData[i].conditions,
                  value: values[`${size}`]
                })

              } else {
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[0], SPDataType.DateTime, CAMLCompare.Geq));
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[1], SPDataType.DateTime, CAMLCompare.Leq));
                params[0].where.push({
                  key: fromData[i].header,
                  filterType: "Ge",
                  value: values.Legalacceptancedate[0]
                })
                params[0].where.push({
                  key: fromData[i].header,
                  filterType: "Le",
                  value: values.Legalacceptancedate[1]
                })
                istrue = false
              }

            }

          }



        }

        // 检索
        
        localStorage.setItem('searchFormParams', JSON.stringify(params)); //缓存高级检索item
        this.theQuery(params)

        this.setParamsByCache(params[0].where); //赋值高级检索弹框params
        // 关闭弹窗
        this.setState({
          visible: false,
          confirmLoading: false,
        });
      }
    });
  }

  ContentToEmpty = () => {
    this.state.form.personreview = undefined
    this.state.form.list = []
    this.state.form.otherSide = ""
    this.state.form.min = ""
    this.state.form.contractName = ""
    this.state.form.contract1 = ""
    this.state.form.contract2 = ""
    this.state.form.dateOf = ""
    this.state.form.dateOf1 = ""
    this.props.form.resetFields();
  }

  getCaption = (obj, state) => {
    var index = obj.lastIndexOf("\-");
    if (state == 0) {
      obj = obj.substring(0, index);
    } else {
      obj = obj.substring(index + 1, obj.length);
    }
    return obj;
  }

  // 检索合同按钮
  retrieve = (text, isBack = 0) => {
    localStorage.setItem('searchType', text)
    if (this.state.inSearchOf) {
      message.warning('检索中');
      return
    }

    this.setState({
      loading: true,
      inSearchOf: true,
    })
    let params: any = [
      {
        logic: "and",
        where: [

        ]
      }
    ];
    // 清空选中条件
    // let params: CamlParam[] = [];
    // test 1.检索  2.废弃  3.申请书  4.合同文件
    if (text == "检索") {
      // 是否检索废弃
      // params.push(new CamlParam("CaseStatus", "有效", SPDataType.Text, CAMLCompare.Eq));
      localStorage.removeItem('searchFormParams'); //删除高级检索的条件缓存
      params[0].where.push({
        key: 'CaseStatus',
        filterType: "Eq",
        value: '有效'
      })

    }

    if (text == "废弃") {
      // 是否检索废弃
      // params.push(new CamlParam("CaseStatus", "废弃", SPDataType.Text, CAMLCompare.Eq));
      params[0].where.push({
        key: 'CaseStatus',
        filterType: "Eq",
        value: '废弃'
      })
      this.ContentToEmpty()
    }
    if (text == "草稿") {
      // 是否检索废弃
      // params.push(new CamlParam("CaseStatus", "草稿", SPDataType.Text, CAMLCompare.Eq));
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      params[0].where.push({
        key: 'CaseStatus',
        filterType: "Eq",
        value: "草稿"
      },{
        key: 'AuthorId',
        filterType: "Eq",
        value: user.Id
      })
      this.ContentToEmpty()
    }
    if (text == "申请书") {
      // 跳转合同申请书文件检索
      location.href = `#/SearchExportFile`
      return
    }
    if (text == "合同文件") {
      // 跳转合同文件检索
      location.href = `#/SearchCaseFile`
      return
    }

    if (text == "无文件检索") {
      // 是否检索废弃
      // params.push(new CamlParam("ContractStatus", "废弃", SPDataType.Text, CAMLCompare.Eq));
      // params.push(new CamlParam("FileAddress", "", SPDataType.Text, CAMLCompare.IsNull));
      params[0].where.push({
        key: 'FileAddress',
        filterType: "Eq",
        value: ''
      })
      // 清空检索内容
      this.ContentToEmpty()
    }


    // 案件名称
    if (this.state.form.contractName != null && this.state.form.contractName != "") {
      // this.fuzzy("ContractName", this.state.form.contractName, "Text", "", "")
      // params.push(new CamlParam("CaseName", this.state.form.contractName, SPDataType.Text, CAMLCompare.Contains));
      params[0].where.push({
        key: 'CaseName',
        filterType: "Contains",
        value: this.state.form.contractName
      })
    }
    // 所属公司
    if (this.state.form.min != null && this.state.form.min != "") {
      // this.fuzzy("Our", this.state.form.min, "Text", "", "")
      // params.push(new CamlParam("BelongsCompany", this.state.form.min, SPDataType.Text, CAMLCompare.Eq));
      params[0].where.push({
        key: 'BelongsCompany',
        filterType: "Eq",
        value: this.state.form.min
      })
    }

    // 判断合同编号1 合同编号2 是否 都有值 
    // 在两输入框全部输入执行 查流水号区间
    if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

      let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;


      let number1 = this.state.form.contract1
      let number2 = this.state.form.contract2
      
      // if (this.state.form.contract1.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract1)) {
      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件


      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })
      //     // params[0].where.push({
      //     //   key: 'VersionNum',
      //     //   filterType: "Ge",
      //     //   value: AfterTheNumber
      //     // })

      //     number1 = this.state.form.contract1


      //   } else {
      //     message.warning('编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // } else {
      //   if (pattern.test(this.state.form.contract1)) {
      //     // contract1
      //     // 截取编号最后三位流水号
      //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
      //     // 我方
      //     var our = this.state.form.contract1.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)

      //     // params.push({
      //     //   item1: 'Our',
      //     //   item2: 'AcceptYear',
      //     //   item3: 'SerialNum',
      //     //   text1: our,
      //     //   text2: year,
      //     //   text3: serialNumber,
      //     //   type: "contractNo2"
      //     // })
      //     // params[0].where.push({
      //     //   key: 'Our',
      //     //   filterType: "Eq",
      //     //   value: our
      //     // })
      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })

      //     number1 = this.state.form.contract1

      //   } else {
      //     message.warning('编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // }

      // if (this.state.form.contract2.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract2)) {
      //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

      //     //
      //     //
      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件
      //     //  我方
      //     // params.push(new CamlParam("Our", our, SPDataType.Text, CAMLCompare.Eq));
      //     // 年份
      //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
      //     //  版本号
      //     // params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

      //     // params[0].where.push({
      //     //   key: 'Our',
      //     //   filterType: "Eq",
      //     //   value: our
      //     // })
      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })
      //     // params[0].where.push({
      //     //   key: 'VersionNum',
      //     //   filterType: "Ge",
      //     //   value: AfterTheNumber
      //     // })

      //     number2 = this.state.form.contract2

      //   } else {
      //     message.warning('编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // } else {
      //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
      //   if (pattern.test(this.state.form.contract2)) {
      //     // contract2
      //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
      //     let serialNumber2 = str2.substring(str2.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber2 = parseInt(serialNumber2)
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于

      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Le",
      //     //   value: serialNumber2
      //     // })

      //     number2 = this.state.form.contract2


      //   } else {
      //     message.warning('编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // }
      if (pattern1.test(this.state.form.contract1)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: number1 + "|" + number2
        })
      } else {
          message.warning('编号格式有误');
          this.setState({
            loading: false,
            inSearchOf: false,
          })
          return
      }
      



    } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract1)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
      //   // params.push({
      //   //   item: 'Title',
      //   //   text: this.state.form.contract1,
      //   //   type: "indexOf"
      //   // })

      //   // params[0].where.push({
      //   //   key: 'Title',
      //   //   filterType: "Contains",
      //   //   value: this.state.form.contract1
      //   // })
      //   params[0].where.push({
      //     key: '',
      //     filterType: "CaseNum",
      //     value: this.state.form.contract1
      //   })

      // } else {
      //   message.warning('编号格式有误');
      //   this.setState({
      //     loading: false,
      //     inSearchOf: false,
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract1)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: this.state.form.contract1
        })
      } else {
          message.warning('编号格式有误');
          this.setState({
            loading: false,
            inSearchOf: false,
          })
          return
      }
      
    } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract2)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
      //   // params.push({
      //   //   item: 'Title',
      //   //   text: this.state.form.contract2,
      //   //   type: "indexOf"
      //   // })

      //   // params[0].where.push({
      //   //   key: 'Title',
      //   //   filterType: "Contains",
      //   //   value: this.state.form.contract2
      //   // })
      //   params[0].where.push({
      //     key: '',
      //     filterType: "CaseNum",
      //     value: this.state.form.contract2
      //   })

      // } else {
      //   message.warning('编号格式有误');
      //   this.setState({
      //     loading: false
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract2)) {
        params[0].where.push({
          key: '',
          filterType: "CaseNum",
          value: this.state.form.contract2
        })
      } else {
        message.warning('编号格式有误');
        this.setState({
          loading: false,
          inSearchOf: false,
        })
        return
      }
      
    }


    // 法务受理担当
    if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.personreview != undefined && this.state.form.personreview != null && this.state.form.personreview.length != 0)) {
      // for (let i = 0; i < this.state.form.list.length; i++) {
      //   // params.push(new CamlParam("Acceptor", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));
      //   params[0].where.push({
      //     key: 'Acceptor',
      //     filterType: "Contains",
      //     value: this.state.form.list[i].props.value.replace("-历史","")
      //   })
      // }
      params[0].where.push( {
        key: 'Acceptor',
        filterType: "MultiUsers",
        value: this.state.form.personreview.map(i => i.replace("-历史","")).join(';')
      })
    }

    // 案件类型 typesofCases
    if (this.state.form.typesofCases != undefined && this.state.form.typesofCases != null && this.state.form.typesofCases != "") {
      // for (let i = 0; i < this.state.form.list.length; i++) {
      // params.push(new CamlParam("CaseType", this.state.form.typesofCases, SPDataType.Text, CAMLCompare.Eq));
      params[0].where.push({
        key: 'CaseType',
        filterType: "Eq",
        value: this.state.form.typesofCases
      })
      // }
    }

    // 开始日期
    if (this.state.form.dateOf != "" && this.state.form.dateOf != null) {
      // 2022-10-20T00:00:00Z
      let size = this.state.form.dateOf
      // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Geq));//我这里用的大于等于，你根据你实际情况来
      params[0].where.push({
        key: 'Created',
        filterType: "Ge",
        value: size
      })
    }

    //结束日期
    if (this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null) {
      let size = this.state.form.dateOf1
      // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
      params[0].where.push({
        key: 'Created',
        filterType: "Le",
        value: size
      })
    }

    if(text = "检索"){
      let form = this.state.form;
      // 
      
      
      if (form.personreview == undefined) {
        localStorage.setItem('searchForm', JSON.stringify(form));
      }else{
        // localStorage.setItem('searchFormList', JSON.stringify(form.list));
        form.list = [];
        localStorage.setItem('searchForm', JSON.stringify(form));
      }
    }

    this.theQuery(params, isBack)
  }


  // 高级检索按钮
  advanced = () => {
    this.setState({
      visible: true,
    });
  }






  public render(): React.ReactElement {
    const { getFieldDecorator } = this.props.form;
    const { visible, confirmLoading } = this.state;
    let defaultDateValue = {};
    if(this.state.form.dateOf != "" && this.state.form.dateOf1 != ""){
      
      defaultDateValue = {
        initialValue: [ // 默认日期
        moment(this.state.form.dateOf, dateFormat),
        moment(this.state.form.dateOf1, dateFormat),
      ],
      };
    }
    return (
      <div className='box'>
        <Spin  spinning={this.state.loading}>
        <div className="box_content">
          <div className="box_top">
            <Row type="flex" justify="end">
              {
                  isHavePermission('SearchCase/moresearch') ? <Col><Button type="primary" className="Button_1" onClick={this.advanced}>高级检索</Button> </Col> : null
                }
              {
                  isHavePermission('SearchCase/searchcase') ? <Col><Button type="primary" onClick={() => { this.retrieve("检索") }}>检索编号</Button> </Col> : null
                }
              {
                  isHavePermission('SearchCase/searchdraft') ? <Col><Button type="primary" onClick={() => { this.retrieve("草稿") }}>检索草稿</Button> </Col> : null
                }
              {
                  isHavePermission('SearchCase/searchabandon') ? <Col><Button type="primary" className="Button_2" onClick={() => { this.retrieve("废弃") }}>检索作废</Button> </Col> : null
                }

              {
                  isHavePermission('SearchCase/casefilesearch') ? <Col><Button type="primary" onClick={() => { this.noFile() }} >无文件检索</Button> </Col> : null
                }

                {
                  isHavePermission('SearchCase/exportcsv') ? <Col><div className="Button_2_1" style={{color: '#fff',cursor: 'pointer'}} onClick={() => this.setState({ExportCsvVisible: true},() => this.exportCsv())}>导出CSV


                  </div> </Col> : null
                }
              {/* <Col>
                {
                  isHavePermission('SearchCase/casefilesearch') ? <Button type="primary" onClick={() => { this.retrieve("合同文件") }} >案件文件检索</Button> : null
                }
              </Col> */}
            </Row>
            <div style={{ height: 16, width: 100 }}></div>
            <Row type="flex" justify="space-between">
              <Col span={7}>
                <Form.Item label="案件编号" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input.Group compact>
                    <Input allowClear style={{ width: '45%', marginRight: 0, textTransform: 'uppercase' }} placeholder="请输入"
                      onChange={(event) => { this.change(event, "contract1") }}
                      value={this.state.form.contract1} />
                    <Input
                      className="site-input-split"
                      style={{
                        width: '10%',
                        background: 'white',
                        pointerEvents: 'none',
                        border: 'none',
                      }}
                      placeholder="~"
                      disabled
                      allowClear
                    />
                    <div></div>
                    <Input
                      className="site-input-right"
                      style={{
                        width: ' 45%',
                      }}
                      placeholder="请输入"
                      onChange={(event) => { this.change(event, "contract2") }}
                      value={this.state.form.contract2}
                      allowClear
                    />
                  </Input.Group>
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="创建日" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  {/* <RangePicker allowClear 
                    placeholder={['选择开始日期', '选择结束日期']}
                    onChange={this.onChangeRangeDate}
                    style={{ width: '100%' }}
                    format={"YYYY-MM-DD"}
                  /> */}
                  {
                    getFieldDecorator('data1', defaultDateValue)(<RangePicker allowClear
                      onChange={this.onChangeRangeDate}
                      style={{ width: '100%' }}
                      format={"YYYY-MM-DD"}
                      placeholder={['选择开始日期', '选择结束日期']}
                    />)
                  }
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="案件名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input
                    className="site-input-right"
                    style={{
                      width: '100%',
                    }}
                    allowClear
                    placeholder="请输入"
                    onChange={(event) => { this.change(event, "contractName") }}
                    value={this.state.form.contractName}
                  />
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label="所属公司" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Select allowClear
                    style={{
                      width: '100%',
                    }}
                    onChange={(event) => { this.handleSelectChange(event, "min") }}
                    placeholder="请选择"
                    value={this.state.form.min}
                  >
                    {
                      this.state.weList.map(element => {
                        return <Option value={element} key={element}>{element}</Option>
                      })
                    }
                  </Select>
                  {/* <Input
                    className="site-input-right"
                    style={{
                      width: '100%',
                    }}
                    placeholder="请输入"
                    onChange={(event) => { this.change(event, "min") }}
                    value={this.state.form.min}
                  /> */}
                </Form.Item>

              </Col>
              <Col span={7}>

                <Form.Item label='案件类型' labelAlign="left" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                  <Select allowClear
                    placeholder="请选择" style={{ width: '100%' }}
                    value={this.state.form.typesofCases}
                    onChange={(event) => { this.handleSelectChange(event, "typesofCases") }}
                  >
                    {
                      this.state.typesofCasesList.map(element => {
                        return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>

              </Col>
              <Col span={7}>
                <Form.Item label='受理担当' labelAlign="left" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>

                  <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '100%' }} value={this.state.form.personreview}
                    onChange={(event, value) => { this.handleSelectChanges(event, value, "personreview") }} maxTagCount={2}>
                    {
                      this.state.personreviewList.map(element => {
                        return <Option value={element.username} key={element.ID}>{element.username}</Option>
                      })
                    }
                  </Select>

                </Form.Item>

              </Col>

            </Row>
          </div>
          <div style={{ height: '24px' }}></div>
          <div className="box_toble">
            <ConfigProvider locale={this.state.local}>
              <Table columns={columns} dataSource={this.state.data}
                pagination={{
                  onChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => {
                      this.getData()
                    })

                  },
                  onShowSizeChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => this.getData())
                  },
                  current: this.state.pager.current,
                  pageSize: this.state.pager.size,
                  hideOnSinglePage: false,
                  total: this.state.totalnum,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultCurrent: 1,
                  showTotal: function (total) {
                    return `总共有 ${total} 条数据`;
                  }
                }} />
            </ConfigProvider>
            {/* <Table columns={columns} dataSource={this.state.data}
              pagination={{
                hideOnSinglePage: false,
                total: this.state.totalnum,
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                defaultCurrent: 1,
                showTotal: function (total) {
                  return `总共有 ${total} 条数据1`;
                }
              }} /> */}
          </div>
          <Modal
            title="导出CSV"
            visible={this.state.ExportCsvVisible}
            onCancel={() => this.setState({ExportCsvVisible: false}, () => dynamicsService.setAbort())}
            maskClosable={false}
            footer={null}
            centered
            destroyOnClose={true}
          >
            {
              this.state.exportData.isLoading ? <div className="spin-text">正在准备数据 <span className="dot-ani"></span></div> : <div className="export_btn" style={{display: 'flex'}}>一共有<span>{this.state.exportData.data.length}</span>条数据，<ExportCsv className="custom" exportData={this.state.exportData} ></ExportCsv></div>
            }
          </Modal>
          <Modal
            destroyOnClose={true}
            visible={visible}
            onCancel={this.handleCancel}
            closable={false}
            footer={null}
            width={'63%'}
          >
            <Form onSubmit={this.handleSubmit} layout='inline' >
              <Row>
                {
                  fromData.map((item, index) => {
                    // type 为 date 日期格式需要强制转化为 moment 格式
                    item.value = item.type == 'date' ? item.value == null ? null : moment(item.value, 'YYYY-MM-DD') : item.value;
                    // item.value = item.type == 'date' ? moment(item.value, 'YYYY-MM-DD') : item.value;
                    return (
                      <Col span={11} offset={index % 2 == 0 ? 0 : 2}>
                        <Form.Item
                          key={index}
                          {...formItemLayout}
                          label={item.text}
                          style={{ display: 'flex', marginTop: '15px' }}
                        >
                          {getFieldDecorator(item.field, {
                            initialValue: item.value,
                            rules: [{
                              required: item.required,
                              message: item.errorMessage
                            }],
                          })(
                            this.switchItem(item)
                          )}
                        </Form.Item>
                      </Col>

                    )
                  })
                }
              </Row>
              <div style={{ height: '24px' }}></div>
              <Row>
                <Col span={3} offset={9}>
                  <Form.Item>
                    <Button type="primary" style={{ padding: ' 0 24px' }} onClick={this.handleSubmit}>检索</Button>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <Form.Item>
                    <Button type="default" style={{ padding: ' 0 24px' }} onClick={this.handleCancel}>取消</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
        </Spin>
        
        {/* <button onClick={this.handleClick}>{children}</button> */}
      </div>

    );
  }
  async exportCsv() {
    this.setState({
      exportData: {
        ...this.state.exportData,
        data: [],
        isLoading: true
      }
    })

    let filter = this.state.filter;
    if (filter.length == 0) { // 如果是刚进来的页面，默认检索有效的数据
      filter = [
        {
          logic: "and",
          where: [
            {
              key: 'CaseStatus',
              filterType: "Eq",
              value: "有效"
            }
          ]
        }
      ];
    }

    let Naturcontract = await Api._getPaged({ Guid: ListGUID.CaseManagement, PageSize: 100000, PageIndex: 1, FilterL: filter });
    // let userList: any = []
    // userList = JSON.parse(localStorage.getItem('usersList'))

    // 
    if(Naturcontract.data) {
      Naturcontract.data.forEach(async element => {
        // for (let i = 0; i < userList.length; i++) {
        //   if (element.AuthorId && userList[i].Id == element.AuthorId) {
        //     element.Author = userList[i].Title
        //   }
        // }
        element.Created = element.Created ? moment(element.Created).format('YYYY-MM-DD') : '';
        element.AcceptTime = element.AcceptTime ? moment(element.AcceptTime).format('YYYY-MM-DD') : '';
        element.LastAnswerTime = element.LastAnswerTime ? moment(element.LastAnswerTime).format('YYYY-MM-DD') : '';
      })
  
      this.setState({
        exportData: {
          ...this.state.exportData,
          data: Naturcontract.data,
          isLoading: false
        }
      })
    }
    
  }

  async getData() {
    this.setState({
      loading: true,
      data: [],
      totalnum: 0
    })

    let filter = this.state.filter;
    if (filter.length == 0) { // 如果是刚进来的页面，默认检索有效的数据
      filter = [
        {
          logic: "and",
          where: [
            {
              key: 'CaseStatus',
              filterType: "Eq",
              value: "有效"
            }
          ]
        }
      ];
    }

    // this.exportCsv()
    localStorage.setItem('PageIndex', JSON.stringify(this.state.pager.current)); //设置页码
    let Naturcontract = await Api._getPaged({ Guid: ListGUID.CaseManagement, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: filter });
    // let userList: any = []
    // userList = JSON.parse(localStorage.getItem('usersList'))
    // 
    if(Naturcontract.data) {
      for (let i = 0; i < Naturcontract.data.length; i++) {
        // let user = userList.filter(item => item.Id == Naturcontract.data[i].AuthorId);
        // Naturcontract.data[i].Author = user.length > 0 ? user[0].Title : ''
        Naturcontract.data[i].Created = Naturcontract.data[i].Created ? moment(Naturcontract.data[i].Created).format('YYYY-MM-DD') : '';
        Naturcontract.data[i].AcceptTime = Naturcontract.data[i].AcceptTime ? moment(Naturcontract.data[i].AcceptTime).format('YYYY-MM-DD') : '';
        Naturcontract.data[i].LastAnswerTime = Naturcontract.data[i].LastAnswerTime ? moment(Naturcontract.data[i].LastAnswerTime).format('YYYY-MM-DD') : '';
      }
  
      this.setState({
        data: Naturcontract.data,
        totalnum: Naturcontract.Total,
        loading: false,
        inSearchOf: false,
      })
    } else {
      this.setState({
        loading: false,
        inSearchOf: false,
      })
    }
    
  }
  //合同性质 合同期限 合同重要性 律师审查 审查担当  公司设置  问题 部门列表
  public async getTest() {
    // 公司设置
    // let Companysettings = await Api._getModel({ Guid: ListGUID.Companies });
    let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany

    fromData[12].options = Companysettings

    // 获取所有列表
    // var countGet = {
    //   Guid: ListGUID.CaseManagement, //表数据
    // };
    // // 获取列表count
    // let getCount = await Api._getCount(countGet);
    // 

    // let ItemCount = "0"

    // if (localStorage.getItem('caseCount') == null) {
    //   ItemCount = getCount.ItemCount
    // } else {
    //   if (localStorage.getItem('caseCount') == getCount.ItemCount) {
    //     localStorage.removeItem('caseCount')
    //     ItemCount = getCount.ItemCount
    //   } else {
    //     ItemCount = localStorage.getItem('caseCount')
    //   }
    // }
    // 

    // 获取分页数据 先获取部分数据本地分页
    // this.state.paging 获取数据开始的id 传 0 从第一个开始查  this.state.pageSize 起始获取的数据条数
    // Naturcontract = await Api.GetListItemsByListGUID(ListGUID.CaseManagement, '', this.state.pageSize, '', 'Created', true, false, this.state.paging);
    // this.state.paging = Naturcontract[Naturcontract.length - 1].ID
    // 
    // Naturcontract = await Api._getPermissionData(ListGUID.CaseManagement, Naturcontract)

    let PersonList = await Api._getModel({ Guid: ListGUID.ReviewOn });
    // 
    const userList = JSON.parse(localStorage.getItem('usersList'));
    PersonList.forEach(async item => {
      item.username = item.Title
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      // 
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }

    });
    let historyReviewOn = PersonList.filter(i => i.Title.includes('-历史'));
    let nowReviewOn = PersonList.filter(i => !i.Title.includes('-历史'))
    PersonList = [...nowReviewOn, ...historyReviewOn];
    // 高级检索
    // 案件类型
    var limit = {
      Guid: ListGUID.CaseType //案件类型
    };
    let timeLimit = await Api._getModel(limit);
    fromData[3].options = timeLimit

    //意见书
    let proposalList = [{ ID: "有", Title: "有" }, { ID: "无", Title: "无" }];
    fromData[5].options = proposalList
    //律师咨询参加
    let participateinList = [{ ID: "有", Title: "有" }, { ID: "无", Title: "无" }];
    fromData[7].options = participateinList
    //保密
    let secrecyList = [{ ID: "是", Title: "是" }, { ID: "否", Title: "否" }];
    fromData[9].options = secrecyList
    let count = 0


    setTimeout(() => {



      this.setState({
        personreviewList: PersonList,
        weList: Companysettings,
        typesofCasesList: timeLimit
      })
    }, 500)



  }

  public async theQuery(params, isBack = 0) {
    if (isBack == 0) {
      this.setState({
        filter: params || [],
        // 检索的时候 是新list 需要把页码重置
        pager: {
          current: 1,
          size: 10
        }
      }, () => {
        this.getData()
      })
    }else{
      this.setState({
        filter: params || [],
        //从详情页返回不重置页码 
      }, () => {
        this.getData()
      })
    }

  }

  // 无文件检索
  // public async theQuery1(params) {

  //   let camlQuery = {
  //     ViewXml: ''
  //   }

  //   //不排序
  //   let orderAge: CamlOrderBy = new CamlOrderBy('Created', 'False');
  //   let demo = Api.buildCamlXml(params, orderAge);

  //   

  //   let Guid = ListGUID.CaseManagement //根据条件检索表数据

  //   camlQuery.ViewXml = demo

  //   let Naturcontract1 = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);
  //   Naturcontract1 = await Api._getPermissionData(ListGUID.CaseManagement, Naturcontract1)
  //   let count = 0;

  //   

  //   if (Naturcontract1.length == 0) {
  //     this.setState({
  //       exportData: {
  //         ...this.state.exportData,
  //         data: Naturcontract1.data,
  //       }
  //     })
  //     // this.exportData.data = Naturcontract1

  //     

  //     setTimeout(() => {
  //       this.setState({
  //         data: arr,
  //         totalnum: arr.length,
  //         loading: false,
  //         inSearchOf: false
  //       })
  //     }, 100)
  //     return
  //   }


  //   let arr = []
  //   Naturcontract1.forEach(async element => {
  //     if (element.FileAddress != null) {
  //       let file = await Api.getFiles(`${ListGUID.CommonLibRelativeUrl} + '/' + ${element.FileAddress}`);
  //       element.file = file
  //       element.dueTime = Date.parse(element.Created);
  //     } else {
  //       element.file = []
  //       element.dueTime = Date.parse(element.Created);
  //     }

  //     if (element.file.length == 0) {
  //       arr.push(element)
  //     }
  //     let Author = await Api.GetUserById(element.AuthorId);
  //     element.Author = Author.Title
  //     element.Created = element.Created.slice(0, 10)
  //     if (element.AcceptTime != null) {
  //       element.AcceptTime = new Date(element.AcceptTime).getFullYear() + '-' + (new Date(element.AcceptTime).getMonth() + 1) + '-' + new Date(element.AcceptTime).getDate()
  //     } else {
  //       element.AcceptTime = ''
  //     }
  //     if (element.LastAnswerTime != null) {
  //       element.LastAnswerTime = new Date(element.LastAnswerTime).getFullYear() + '-' + (new Date(element.LastAnswerTime).getMonth() + 1) + '-' + new Date(element.LastAnswerTime).getDate()
  //     } else {
  //       element.LastAnswerTime = ''
  //     }
  //     count++
  //     if (Naturcontract1.length == count) {
  //       setTimeout(() => {
  //         arr = arr.sort(function (a, b) {
  //           return b.dueTime - a.dueTime;
  //         });
  //         
  //         this.setState({
  //           exportData: {
  //             ...this.state.exportData,
  //             data: arr,
  //           }
  //         })
  //         // this.exportData.data = arr
  //         this.setState({
  //           data: arr,
  //           totalnum: arr.length,
  //           loading: false,
  //           inSearchOf: false
  //         })
  //       }, 100)
  //     }
  //   });

  // }


}
export default Form.create()(SearchCase)